<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>红包掉落js版</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" charset="UTF-8"> 
<style>
	
	:root {
		--clr-primary: #ee6352;
		--clr-secondary: #d16e8d;
		--clr-accent: #F7F7FF;
		--clr-gradient: linear-gradient(-90deg, var(--clr-primary), var(--clr-secondary));
		--ff-title: bungee, sans-serif;
		--ff-body: canada-type-gibson,sans-serif;
		--fw-body: 300;
		--fw-bold: 800;
		--fw-title: 400;
		--fw-number: 800;
	}
	body,p{
		margin: 0;
		padding: 0;
	}
    .bg{
            width: 100vw;
            height: 100vh;
            background-repeat: no-repeat;
            background-size: 100% 100%;
            background-image: url(https://img.alicdn.com/imgextra/i4/826052692/O1CN01Ho8jJp1Vkyrj0QClq_!!826052692.png);
	 
    		position: relative;
      } 
	  .target{
			width: 60vw;
			height: 20vh;
			background-repeat: no-repeat;
			background-size: contain;
            background-image: url(https://img.alicdn.com/imgextra/i3/826052692/O1CN01911GsZ1VkyrtJEFvO_!!826052692.png);
			display: inline-block;
   			position: absolute;
			top: 80vh;
		
	  }
	  .score{
		  font-size: 4vh;
		  margin: 0 0 0 2vh;
		  /* text-shadow: 3px 3px 0 yellow, 6px 6px 0 blue, 9px 9px red, 12px 12px 0 black; */
		  text-shadow:  2px 2px 0 yellow, 4px 4px 0  red;
			font-family: var(--ff-title);
			font-weight: var(--fw-title);
			text-transform: uppercase;
			font-size: calc(2rem + 5vw);
			text-align: center;
			margin: 0;
			color: var(--clr-primary);
	  }
	  .dropper1{
		  width: 10vw;
		  height: 15vw; 
		  position: absolute;
		  background-repeat: no-repeat;
			background-size: contain;
            background-image: url( https://img.alicdn.com/imgextra/i3/826052692/O1CN01QyxlOF1VkyrnE5Rc2_!!826052692.png);
			display: inline-block;
	  }
	  .dropper2{
		  width: 10vw;
		  height: 15vw; 
		  position: absolute;
		  background-repeat: no-repeat;
			background-size: contain;
            background-image: url(https://img.alicdn.com/imgextra/i4/826052692/O1CN01gUnKJc1VkyroblryF_!!826052692.png);
			display: inline-block;
	  }
</style>
</head>
<body>
	<div id="container" v-cloak>
        <div class="bg">
			<div class="score"></div>
			<div class="target" id="target"></div>
        </div>
    </div>
<script>
	var target =  null; //拖拽物
	var score = 0 ; //分数
	var duration = 16; //计时器间隔
	var speed = 10;  //下落速度
	var baseSpeed = 10;  //初始下落速度
	var number = 1; //下落序号
	window.onload = function(){
		tuodong()
		diaoluo()
    }
	//拖动
	function tuodong(){
			target =  document.getElementById('target');
			var startX = 0; // 获取手指初始坐标
			var startY = 0;
			var x = 0; // 获得盒子原来的位置
			var y = 0;
			// 手指触摸
			target.addEventListener('touchstart', function(e) {
				// 获取手指初始坐标
				startX = e.targetTouches[0].pageX;
				startY = e.targetTouches[0].pageY;
				x = this.offsetLeft;
				y = this.offsetTop;
				//   this.style.boxShadow = '0 0 15px rgba(0, 0, 0, .6)';
			});
			// 手指离开
			target.addEventListener('touchend', function(e) {
				//   this.style.boxShadow = '';
			});
		
			// 手指按住移动
			target.addEventListener('touchmove', function(e) {
				// 计算手指的移动距离：手指移动之后的坐标减去手指初始的坐标
				var moveX = e.targetTouches[0].pageX - startX;
				var moveY = 0// e.targetTouches[0].pageY - startY;
				// 移动盒子 盒子原来的位置 + 手指移动的距离
				this.style.left = x + moveX + 'px';
				this.style.top = y + moveY + 'px';
				e.preventDefault(); // 阻止屏幕滚动的默认行为
			});

	}
	//掉落
	function diaoluo(){
		setInterval(() => {
			createDropper(number)
			number++
			speed = Math.ceil(number/10)+baseSpeed;
		}, 600);
	}
	//单个掉落
	function createDropper(number){
		
		var dropper = document.createElement("div");
			
			//样式随机
			if(Math.random()-0.5>0){
				dropper.setAttribute("class","dropper1");
			}else{
				dropper.setAttribute("class","dropper2");
			}
			//左右位置随机
			var x = document.documentElement.clientWidth /4* Math.ceil(Math.random()*4)-document.documentElement.clientWidth*0.2;
			dropper.style.left = x+ 8+'px';
			
			//追加到页面
			document.querySelector('.bg').appendChild(dropper);

		var timer = setInterval(function () {
			var y = parseInt(dropper.style.top)||0;

			if(y>document.documentElement.clientHeight*0.8){
				
				var hit = hitTestRectangle(dropper.getBoundingClientRect(),target.getBoundingClientRect()) //获取该元素在当前窗口视图区域的位置
				console.log(number,hit);
				getScore(hit);
				// dropper.style.display='none';
				document.querySelector('.bg').removeChild(dropper)
				clearInterval(timer);
			}else{
				dropper.style.top = y+ speed+'px';
			}
		},duration)
		//可以使用 requestAnimationFrame cancelAnimationFrame 做优化
	}

	//碰撞检测
	function hitTestRectangle(r1, r2) {

		//Define the variables we'll need to calculate
		let hit, combinedHalfWidths, combinedHalfHeights, vx, vy;

		//hit will determine whether there's a collision
		hit = false;

		//Find the center points of each sprite
		r1.centerX = r1.x + r1.width / 2;
		r1.centerY = r1.y + r1.height / 2;
		r2.centerX = r2.x + r2.width / 2;
		r2.centerY = r2.y + r2.height / 2;

		//Find the half-widths and half-heights of each sprite
		r1.halfWidth = r1.width / 2;
		r1.halfHeight = r1.height / 2;
		r2.halfWidth = r2.width / 2;
		r2.halfHeight = r2.height / 2;

		//Calculate the distance vector between the sprites
		vx = r1.centerX - r2.centerX;
		vy = r1.centerY - r2.centerY;

		//Figure out the combined half-widths and half-heights
		combinedHalfWidths = r1.halfWidth + r2.halfWidth;
		combinedHalfHeights = r1.halfHeight + r2.halfHeight;

		//Check for a collision on the x axis
		if (Math.abs(vx) < combinedHalfWidths) {

		//A collision might be occurring. Check for a collision on the y axis
		if (Math.abs(vy) < combinedHalfHeights) {

			//There's definitely a collision happening
			hit = true;
		} else {

			//There's no collision on the y axis
			hit = false;
		}
		} else {

		//There's no collision on the x axis
			hit = false;
		}

		//`hit` will be either `true` or `false`
		return hit;
	}

	//得分
	function getScore(hit){
		score = score+(hit?2:-3);
		document.querySelector('.score').innerHTML = score;
	}
</script>

</body>
</html>
